#!/bin/bash

#turn on debug mode by following env. variable _DEBUG=1

PS4='$LINENO:'
[ -z "$CRYPTSETUP_PATH" ] && CRYPTSETUP_PATH=".."
CRYPTSETUP=$CRYPTSETUP_PATH/cryptsetup

CRYPTSETUP_VALGRIND=../.libs/cryptsetup
CRYPTSETUP_LIB_VALGRIND=../.libs

START_DIR=$(pwd)

IMG=luks2-backend.img
ORIG_IMG=luks2_valid_hdr.img
TST_IMGS=$START_DIR/luks2-images

GEN_DIR=generators

FAILS=0

[ -z "$srcdir" ] && srcdir="."

function remove_mapping()
{
	rm -rf $IMG $TST_IMGS >/dev/null 2>&1
}

function fail()
{
	[ -n "$1" ] && echo "$1"
	echo "FAILED backtrace:"
	while caller $frame; do ((frame++)); done
	cd $START_DIR
	remove_mapping
	exit 2
}

fail_count()
{
	echo "$1"
	FAILS=$((FAILS+1))
}

function skip()
{
	[ -n "$1" ] && echo "$1"
	exit 77
}

function prepare() # $1 dev1_size
{
	remove_mapping

	test -d $TST_IMGS || mkdir $TST_IMGS

	test -e $ORIG_IMG || xz -dkc $srcdir/$ORIG_IMG.xz >$ORIG_IMG
	cp $ORIG_IMG $TST_IMGS
	cp $ORIG_IMG $IMG
}

function test_load()
{
	local _debug=

	test -z "$_DEBUG" || _debug="--debug"

	case "$1" in
	R)
		if [ -n "$_debug" ]; then
			$CRYPTSETUP luksDump $_debug $IMG
		else
			$CRYPTSETUP luksDump $_debug $IMG > /dev/null 2>&1
		fi
		test $? -eq 0 || return 1
		;;
	F)
		if [ -n "$_debug" ]; then
			$CRYPTSETUP luksDump $_debug $IMG
		else
			$CRYPTSETUP luksDump $_debug $IMG > /dev/null 2>&1
		fi
		test $? -ne 0 || return 1
		;;
	*)
		fail "Internal test error"
		;;
	esac
}

function RUN()
{
	echo -n "Test image: $1..."
	cp $TST_IMGS/$1 $IMG || fail "Missing test image"
	test_load $2 "$3"
	if [ $? -ne 0 ]; then
		fail_count "$3"
	else
		echo "OK"
	fi
}

function valgrind_setup()
{
	which valgrind >/dev/null 2>&1 || fail "Cannot find valgrind."
	[ ! -f $CRYPTSETUP_VALGRIND ] && fail "Unable to get location of cryptsetup executable."
	export LD_LIBRARY_PATH="$CRYPTSETUP_LIB_VALGRIND:$LD_LIBRARY_PATH"
}

function valgrind_run()
{
	INFOSTRING="$(basename ${BASH_SOURCE[1]})-line-${BASH_LINENO[0]}" ./valg.sh ${CRYPTSETUP_VALGRIND} "$@"
}

[ -n "$VALG" ] && valgrind_setup && CRYPTSETUP=valgrind_run

which jq >/dev/null 2>&1 || skip "Cannot find jq, test skipped."

prepare

echo "[0] Generating test headers"
cd $srcdir/$GEN_DIR
for scr in ./generate-*.sh; do
	echo -n "$(basename $scr)..."
	$scr $TST_IMGS $TST_IMGS/$ORIG_IMG || fail "Header generator $scr failed: '$?'"
	echo "done"
done
cd $START_DIR

echo "[1] Test basic auto-recovery"
RUN luks2-invalid-checksum-hdr0.img "R" "Failed to recover from trivial header corruption at offset 0"
# TODO: check epoch is incresed after recovery
# TODO: check only sectors related to corrupted hdr at offset 0 are written (dmstats tool/differ.c)

RUN luks2-invalid-checksum-hdr1.img "R" "Failed to recover from trivial header corruption at offset 16384"
# TODO: check epoch is incresed after recovery
# TODO: check only sectors related to corrupted hdr at offset 16384 are written (dmstats tool/differ.c)

RUN luks2-invalid-checksum-both-hdrs.img "F" "Failed to recognise corrupted header beyond repair"

echo "[2] Test ability to auto-correct mallformed json area"
RUN luks2-corrupted-hdr0-with-correct-chks.img "R" "Failed to auto correct malformed json area at offset 512"
# TODO: check epoch is incresed after recovery
# TODO: check only sectors related to corrupted hdr at offset 0 are written (dmstats tool/differ.c)

RUN luks2-corrupted-hdr1-with-correct-chks.img "R" "Failed to auto correct malformed json area at offset 16896"
# TODO: check epoch is incresed after recovery
# TODO: check only sectors related to corrupted hdr at offset 16384 are written (dmstats tool/differ.c)

RUN luks2-correct-full-json0.img "R" "Failed to parse full and correct json area"
# TODO: detect noop (norecovery, epoch untouched)
# TODO: check epoch is NOT incresed after recovery of secondary header

# these tests auto-correct json in-memory only. It'll get fixed on-disk after write operation
RUN luks2-argon2-leftover-params.img   "R" "Failed to repair keyslot with old argon2 parameters."
RUN luks2-pbkdf2-leftover-params-0.img "R" "Failed to repair keyslot with old pbkdf2 parameters."
RUN luks2-pbkdf2-leftover-params-1.img "R" "Failed to repair keyslot with old pbkdf2 parameters."

# Secondary header is always broken in following tests
echo "[3] Test LUKS2 json area restrictions"
RUN luks2-non-null-byte-beyond-json0.img		"F" "Failed to detect illegal data right beyond json data string"
RUN luks2-non-null-bytes-beyond-json0.img		"F" "Failed to detect illegal data in json area"
RUN luks2-missing-trailing-null-byte-json0.img		"F" "Failed to detect missing terminal null byte"
RUN luks2-invalid-opening-char-json0.img		"F" "Failed to detect invalid opening character in json area"
RUN luks2-invalid-object-type-json0.img			"F" "Failed to detect invalid json object type"
RUN luks2-overlapping-areas-c0-json0.img		"F" "Failed to detect two exactly same area specifications"
RUN luks2-overlapping-areas-c1-json0.img		"F" "Failed to detect two intersecting area specifications"
RUN luks2-overlapping-areas-c2-json0.img		"F" "Failed to detect two slightly intersecting area specifications"
RUN luks2-area-in-json-hdr-space-json0.img		"F" "Failed to detect area referencing LUKS2 header space"
RUN luks2-missing-keyslot-referenced-in-digest.img	"F" "Failed to detect missing keyslot referenced in digest"
RUN luks2-missing-segment-referenced-in-digest.img	"F" "Failed to detect missing segment referenced in digest"
RUN luks2-missing-keyslot-referenced-in-token.img	"F" "Failed to detect missing keyslots referenced in token"
RUN luks2-keyslot-missing-digest.img			"F" "Failed to detect missing keyslot digest."
RUN luks2-keyslot-too-many-digests.img			"F" "Failed to detect keyslot has too many digests."

echo "[4] Test integers value limits"
RUN luks2-uint64-max-segment-size.img			"R" "Validation rejected correct value"
RUN luks2-uint64-overflow-segment-size.img		"F" "Failed to detect uint64_t overflow"
RUN luks2-uint64-signed-segment-size.img		"F" "Failed to detect negative value"

echo "[5] Test segments validation"
RUN luks2-segment-missing-type.img			"F" "Failed to detect missing type field"
RUN luks2-segment-wrong-type.img			"F" "Failed to detect invalid type field"
RUN luks2-segment-missing-offset.img			"F" "Failed to detect missing offset field"
RUN luks2-segment-wrong-offset.img			"F" "Failed to detect invalid offset field"
RUN luks2-segment-missing-size.img			"F" "Failed to detect missing size field"
RUN luks2-segment-wrong-size-0.img			"F" "Failed to detect invalid size field"
RUN luks2-segment-wrong-size-1.img			"F" "Failed to detect invalid size field"
RUN luks2-segment-wrong-size-2.img			"F" "Failed to detect invalid size field"
RUN luks2-segment-crypt-missing-encryption.img		"F" "Failed to detect missing encryption field"
RUN luks2-segment-crypt-wrong-encryption.img		"F" "Failed to detect invalid encryption field"
RUN luks2-segment-crypt-missing-ivoffset.img		"F" "Failed to detect missing iv_tweak field"
RUN luks2-segment-crypt-wrong-ivoffset.img		"F" "Failed to detect invalid iv_tweak field"
RUN luks2-segment-crypt-missing-sectorsize.img		"F" "Failed to detect missing sector_size field"
RUN luks2-segment-crypt-wrong-sectorsize-0.img		"F" "Failed to detect invalid sector_size field"
RUN luks2-segment-crypt-wrong-sectorsize-1.img		"F" "Failed to detect invalid sector_size field"
RUN luks2-segment-crypt-wrong-sectorsize-2.img		"F" "Failed to detect invalid sector_size field"
RUN luks2-segment-unknown-type.img			"R" "Validation rejected segment with all mandatory fields correct"
RUN luks2-segment-two.img				"R" "Validation rejected two valid segments"
RUN luks2-segment-wrong-flags.img			"F" "Failed to detect invalid flags field"
RUN luks2-segment-wrong-flags-element.img		"F" "Failed to detect invalid flags content"

echo "[6] Test metadata size and keyslots size (config section)"
RUN luks2-invalid-keyslots-size-c0.img			"F" "Failed to detect too large keyslots_size in config section"
RUN luks2-invalid-keyslots-size-c1.img			"F" "Failed to detect unaligned keyslots_size in config section"
RUN luks2-invalid-keyslots-size-c2.img			"F" "Failed to detect too small keyslots_size config section"
RUN luks2-invalid-json-size-c0.img			"F" "Failed to detect invalid json_size config section"
RUN luks2-invalid-json-size-c1.img			"F" "Failed to detect invalid json_size config section"
RUN luks2-invalid-json-size-c2.img			"F" "Failed to detect mismatching json size in config and binary hdr"
RUN luks2-metadata-size-32k.img				"R" "Valid 32KiB metadata size failed to validate"
RUN luks2-metadata-size-64k.img				"R" "Valid 64KiB metadata size failed to validate"
RUN luks2-metadata-size-64k-inv-area-c0.img		"F" "Failed to detect keyslot area trespassing in json area"
RUN luks2-metadata-size-64k-inv-area-c1.img		"F" "Failed to detect keyslot area overflowing keyslots area"
RUN luks2-metadata-size-64k-inv-keyslots-size-c0.img	"F" "Failed to detect keyslots size overflowing in data area"
RUN luks2-metadata-size-128k.img			"R" "Valid 128KiB metadata size failed to validate"
RUN luks2-metadata-size-256k.img			"R" "Valid 256KiB metadata size failed to validate"
RUN luks2-metadata-size-512k.img			"R" "Valid 512KiB metadata size failed to validate"
RUN luks2-metadata-size-1m.img				"R" "Valid 1MiB metadata size failed to validate"
RUN luks2-metadata-size-2m.img				"R" "Valid 2MiB metadata size failed to validate"
RUN luks2-metadata-size-4m.img				"R" "Valid 4MiB metadata size failed to validate"
RUN luks2-metadata-size-16k-secondary.img		"R" "Valid 16KiB metadata size in secondary hdr failed to validate"
RUN luks2-metadata-size-32k-secondary.img		"R" "Valid 32KiB metadata size in secondary hdr failed to validate"
RUN luks2-metadata-size-64k-secondary.img		"R" "Valid 64KiB metadata size in secondary hdr failed to validate"
RUN luks2-metadata-size-128k-secondary.img		"R" "Valid 128KiB metadata size in secondary hdr failed to validate"
RUN luks2-metadata-size-256k-secondary.img		"R" "Valid 256KiB metadata size in secondary hdr failed to validate"
RUN luks2-metadata-size-512k-secondary.img		"R" "Valid 512KiB metadata size in secondary hdr failed to validate"
RUN luks2-metadata-size-1m-secondary.img		"R" "Valid 1MiB metadata size in secondary hdr failed to validate"
RUN luks2-metadata-size-2m-secondary.img		"R" "Valid 2MiB metadata size in secondary hdr failed to validate"
RUN luks2-metadata-size-4m-secondary.img		"R" "Valid 4MiB metadata size in secondary hdr failed to validate"

remove_mapping

test $FAILS -eq 0 || fail "($FAILS wrong result(s) in total)"
